<?php
namespace control;
/*
*销售跟踪表类
*/

class saleTrackClass extends adIndexClass
{
    private const page = 'saleTrack';
    private const title = '销售跟踪表';

    /**
     * 字段初始化
     */
    public function fieldInit($fun): array
    {
        switch ($fun) {
            default:
                $tr = [
                    'recordDate'          => [
                        'name'  => '单据日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'orderNo' => [
                        'name'  => "单据编号",
                        'width' => 200,
                        'sort' => 1,
                    ],
                    'contract'  => [
                        'name'  => "合同编号",
                        'width' => 200,
                    ],
                    'companyName'         => [
                        'name'  => '客户',
                        'width' => 200,
                    ],
                    'manager'          => [
                        'name'  => '销售员',
                        'width' => 100,
                    ],
                    'num'          => [
                        'name'  => '订单总数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'send_num'          => [
                        'name'  => '发货总数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'refund_num'          => [
                        'name'  => '退货总数量',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'residue'          => [
                        'name'  => '剩余总数量',
                        'width' => 100,
                    ],
                    'completion_rate'          => [
                        'name'  => '完成率',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'deliveryDate'          => [
                        'name'  => '交货日期',
                        'width' => 100,
                        'sort' => 1,
                    ],
                    'state'          => [
                        'name'  => '状态',
                        'width' => 100,
                    ]
                ];
        }
        return $tr;
    }

    /*列表页-查询条件*/
    public function homeOptions($isAsync = true)
    {
        //生成查询表单
        $html = $this->tableShow([
            [
                [
                    "单据编号" => text(array("name" => "orderNo")),
                    "合同编号"   => text(array("name" => "contractNo")),
                    '状态' => select(array('name'=>'state','option'=>['待出库','部分出库','已出库'])),
                ],
                [
                    '客户名称'  => clientProfileClass::kehuSelect(array('title' => '')),
                    "销售员" => selectMultiple(["name" => "stid", 'table' => "staff", 'sqlId' => 'stid', 'sqlField' => 'name', 'class' => 'width200']),
                    '单据日期' => text(array("name" => "createTime", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ],
                [
                    "交货日期" => text(array("name" => "time", 'laydate' => ['type' => 'date', 'range' => '~'])),
                ]
            ]
        ],1);
        //返回
        if (!$isAsync) {
            return $html;
        } else {
            return json_encode(['html' => $html], 320);
        }
    }

    /*列表-查询条件*/
    public function home()
    {
        $html = $this->homeOptions(false);
        //控件
        $button = "";
        if ($this->power(self::page, "export")) {
            $button .="<span class='spanButton' onclick=\"layer('importTemplate','exportFrame',{cla:'".self::page."'})\">导出</span>";
        }
        //返回
        return $this->homeFun($this->search($html, layout: 'pop', toolButton: $button));
    }

    /*客户列表-查询结果*/
    public function homeSearch()
    {
        //like查询数组
        $like = array(
            "orderNo" => $this->post('orderNo'),//证件编号
        );
        //全等查询数组
        $equal = array(
            "khid" => $this->post('khid'),
            "stid" => $this->post('stid'),
            "coid"=>self::$coid,
            "state"=>'已确认'
        );
        $and = match ($this->post('state')) {
            '待出库' => " and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from sale_send_order_detail where saleOrderMxId in (select id from sale_order_detail where orderId = a.id))) = 0",
            '部分出库' => " and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from sale_send_order_detail where saleOrderMxId in (select id from sale_order_detail where orderId = a.id))) > 0 and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from sale_send_order_detail where saleOrderMxId in (select id from sale_order_detail where orderId = a.id))) < a.num",
            '已出库' => " and (select ifnull(sum(num),0) from inventory_detail where sourceId in (select id from sale_send_order_detail where saleOrderMxId in (select id from sale_order_detail where orderId = a.id))) = a.num",
            default=>'',
        };
        if ($this->post('contractNo')) {
            $and.=" and b.contractId in (select id from sales_contract where orderNo like '%".$this->post('contractNo')."%' and coid = '".self::$coid."')";
        }
        if ($this->post('createTime')) {
            //单据日期
            $and .= self::timeComparison($this->post('createTime'),field: 'recordDate');
        }
        if ($this->post('time')) {
            //单据日期
            $and .= self::timeComparison($this->post('createTime'),field: 'deliveryDate');
        }
        //获取查询结果
        $where = search(array("like" => $like, "=" => $equal)) . $and;
        //排序
        $orderBy = $this->listSort(array(
            "search"  => $this->post('list_sort_key') ?: 'recordDate desc,time',
            "sort" => $this->post('list_sort') ?: "desc",
            "array"   => array(),
        ));
        $page = $this->page(array("table" => "sale_order", "where" => $where, "order" => $orderBy['orderBy']));
        $_SESSION[self::page]['sql'] = $page['fullSql'];
        //获取自定义字段参数
        $installSearch = $this->installSearch();
        $body          = [];
        //表格控件区
        $liButton = array(
            $this->checkAll("listForm", "listId")
        );
        //获取记录
        $url = root . "control/adIndex.html?cla=" . self::page;
        //获取记录
        foreach ($page['array'] as $array) {
            //列表控件
            $dominate = array(
                "box"    => array("name" => "listId", "value" => $array['id']),
                "detail" => array("title" => self::title . "详情", "click" => "newIframe('" . self::title . "详情','" . $url . "&fun=detail&id=" . $array['id'] . "')"),
            );
            /*//已出库数量
            $out_num = find(array('table'=>'inventory_detail','where'=>"sourceId in (select id from sale_send_order_detail where saleOrderMxId in (select id from sale_order_detail where orderId = '$array[id]'))",'sum'=>"num"));
            //退货数量
            $refund_num = find(array('table'=>'sale_refund_order_detail as mx left join sale_refund_order as a on mx.orderId = a.id','where'=>" a.state = '已确认' and mx.sourceId in (select id from sale_send_order_detail where saleOrderMxId in (select id from sale_order_detail where orderId = '$array[id]'))",'sum'=>"num"));
            $refund_num += find(array('table'=>'sale_refund_order_detail as mx left join sale_refund_order as a on mx.orderId = a.id','where'=>" a.state = '已确认' and mx.sourceId in (select id from sale_order_detail where orderId = '$array[id]')",'sum'=>"num"));
            $state = '待出库';
            $num = find(array('table'=>'sale_order_detail','where'=>"orderId = '$array[id]'",'sum'=>"num"));
            if ($num > $out_num && $out_num >0){
                $state = '部分出库';
            }elseif($out_num >= $num && $out_num >0){
                $state = '已出库';
            }
            $completionRate = $num==0?0:round(($out_num-$refund_num)/$num*100,1).'%';*/
            $liButton[] = $this->dominate($dominate);
            //本行初始化
            $row = [];
            foreach ($installSearch['key'] as $key) {
                switch ($key) {
                    case "contract":
                        $contract = query('sales_contract',"id = '$array[contractId]'");
                        $row[] = $contract['orderNo'];
                        break;
                    case "companyName":
                        $kehu = query('kehu',"khid = '$array[khid]'");
                        $row[] = $kehu['companyName'];
                        break;
                    case "manager":
                        $row[] = self::findStaff($array['manager']);
                        break;
                    case "num":
                    case "send_num":
                    case "refund_num":
                        $row[] = self::lostZero($array[$key], 'numPrecision');
                        break;
                    case "residue":
                        $row[] = self::formattingFigure($array['num'] - $array['send_num'] + $array['refund_num'], 'numPrecision');
                        break;
                    case "completion_rate":
                        $row[] = ($array['completion_rate'] * 100) . '%';
                        break;
                    case "state":
                        $state = '待出库';
                        if ($array['num'] > $array['send_num'] && $array['send_num'] >0){
                            $state = '部分出库';
                        }elseif($array['send_num'] >= $array['num'] && $array['send_num'] >0){
                            $state = '已出库';
                        }
                        $row[] = $state;
                        break;
                    default:
                        $row[] = isset($array[$key]) && $array[$key] ? $array[$key] : '';
                }
            }
            $body[] = $row;
        }
        //控件
        $button = "";
        /*$total = find([
            "table" => "sale_order_detail",
            'field'=>"ifnull(sum(num),0) as num",
            "single" => "orderId in (select id from sale_order where 1=1 {$where})",
        ]);
        $outNum = find([
            "table" => "inventory_detail",
            'field'=>"ifnull(sum(num),0) as num",
            "single" => "sourceId in (select id from sale_send_order_detail where saleOrderMxId in (select id from sale_order_detail where orderId in (select id from sale_order where 1=1 {$where})))",
        ]);
        $button   .= componentClass::spanLabel('订单数量合计', self::formattingFigure($total['num']));
        $button   .= componentClass::spanLabel('发货数量合计', self::formattingFigure($outNum['num'],'numPrecision'));*/
        $numTotal = find(array(
            'table' => "sale_order",
            'single' => $where,
            'field' => "ifnull(sum(num),0) as num,ifnull(sum(send_num),0) as send_num,ifnull(sum(refund_num),0) as refund_num,ifnull(sum(money),0) as money"
        ));
        $total = [
            'num' => self::lostZero($numTotal['num'], 'numPrecision'),
            'send_num' => self::lostZero($numTotal['send_num'], 'numPrecision'),
            'refund_num' => self::lostZero($numTotal['refund_num'], 'numPrecision'),
            'residue' => self::formattingFigure($numTotal['num'] - $numTotal['send_num'] + $numTotal['refund_num'], 'numPrecision'),
            'money' => self::lostZero($numTotal['money']),
        ];
        //生成页面
        $li = $this->li(array(
            "body" => $body,
            "install" => $installSearch,
            "button" => array("html" => $liButton),
            "orderBySign" => $orderBy,
            "page" => $page['para'],
            "total" => $total,
        ));
        //返回
        $json['html'] = $page['hint'] . $button . "<form name='listForm'>" . $li . "</form>" . $page['button'] . clear;
        return json_encode($json, 320);
    }

    /**
     * 导出按钮
     * @param $checkBoxName
     * @param $url
     * @return string
     */
    public static function exportOperation($checkBoxName,$url): string
    {
        return <<<eof
<span onclick="exportData('$url')" class='spanButton'>导出</span>\n
<script>
function exportData(url) {
      let arr = [];
    $("input[name='{$checkBoxName}[]']:checked").each(function () {
        if ($(this).val() && $(this).val() !== 'on') {
            arr.push($(this).val());
        }
    });
    let vals = arr.join(",");
    location.href = url+"&listId="+vals;
}
</script>
eof;

    }


    /**
     * 销售发货已出库的数量
     * @param $saleOrderMxId
     * @param $toUnit
     * @return float|int
     */
    private function outInventoryNum($saleOrderMxId,$toUnit): float|int
    {
        //已出库数量
        $num=0;
        $all = find(array('table'=>'inventory_detail','where'=>"sourceId in (select id from sale_send_order_detail where saleOrderMxId = '$saleOrderMxId')"));
        foreach ($all['array'] as $array){
            $num+=machiningOrderClass::material_num_change($array['materialId'],$array['unit'],$toUnit,$array['num']);
        }
        return self::formattingFigure($num,'numPrecision');
    }

    /**
     * 采购收货已入库的数量
     * @param $purchaseOrderMxId
     * @param $toUnit
     * @return float|int
     */
    private function inInventoryNum($purchaseOrderMxId,$toUnit): float|int
    {
        //已出库数量
        $num=0;
        $all = find(array('table'=>'inventory_detail','where'=>"sourceId in (select id from purchase_get_order_detail where sourceId = '$purchaseOrderMxId')"));
        foreach ($all['array'] as $array){
            $num+=machiningOrderClass::material_num_change($array['materialId'],$array['unit'],$toUnit,$array['num']);
        }
        return self::formattingFigure($num,'numPrecision');
    }
    /*详情页*/
    public function detail(): string
    {
        $info = query('sale_order', " id = '{$this->get('id')}'");
        if (empty($info['id'])) {
            $html = '未找到此销售单';
        } else {
            //菜单
            $data = array(
                "id" => $info['id'],
            );
            static::rSet(self::$stid.self::page.'OrderNo',$info['orderNo']);
            /****销售******/
            $reportTr[] = ['单据日期', '单据编号', '合同编号', '客户','销售员', '产品编码', '产品名称',  '规格型号', '单位', '销售数量', '发货数量', '未发货数量','交货日期','最后出库日期','状态'];
            $result = find(array(
                "table" => "sale_order_detail as a join sale_order as b on a.orderId = b.id join material as c on c.id = a.materialId",
                'field'=>"a.*,b.orderNo,b.recordDate,b.contractId,b.khid,b.stid,c.code,c.name as materialName,c.model,b.deliveryDate",
                "where" => "b.coid = '".self::$coid."' and b.id = '$info[id]' order by a.list desc,a.time desc"));
            static::rSet(self::$stid.self::page.'SaleSql',$result['sql']);
            $sale_num = $send_num = 0;
            foreach ($result['array'] as $array) {
                $contract = query('sales_contract',"id = '$array[contractId]'");
                $kehu = query('kehu',"khid = '$array[khid]'");
                //已出库数量
                $out_num = $this->outInventoryNum($array['id'],$array['unit']);

                $state = '待出库';
                if ($array['num'] > $out_num && $out_num >0){
                    $state = '部分出库';
                }elseif($out_num >= $array['num'] && $out_num >0){
                    $state = '已出库';
                }
                //最后出库日期
                $last = find(array(
                    'table'=>'inventory_detail as a join inventory as b on a.orderId = b.id',
                    'field'=>"date(b.time) as lastDate",
                    'single'=>"a.sourceId in (select id from sale_send_order_detail where saleOrderMxId = '$array[id]') order by b.time desc"
                ));
                $reportTr[] = array(
                    $array['recordDate'],
                    $array['orderNo'],
                    $contract['orderNo'],
                    $kehu['companyName'],
                    self::findStaff($array['stid']),
                    $array['code'],
                    $array['materialName'],
                    $array['model'],
                    $array['unit'],
                    self::lostZero($array['num'],'numPrecision'),
                    self::lostZero($out_num,'numPrecision'),
                    self::lostZero($array['num']-$out_num,'numPrecision'),
                    $array['deliveryDate'],
                    isset($last['lastDate'])&&$state!='待出库'?$last['lastDate']:'',
                    $state
                );
                $sale_num += $array['num'];
                $send_num += $out_num;
            }
            $slae_total_tr = [
                9 => self::lostZero($sale_num, 'numPrecision'),
                10 => self::lostZero($send_num, 'numPrecision'),
                11 => self::lostZero($sale_num - $send_num, 'numPrecision'),
            ];

            /****采购******/
            $materialTr[] = ['单据日期','采购订单号','合同编号','供应商','产品编码', '产品名称',  '规格型号', '单位', '采购数量', '收货数量', '未收货数量',  '交货日期', '最后入库日期', '状态'];
            $all = find(array(
                'table'=>"purchase_order as a join purchase_order_detail as b on a.id = b.orderId",
                'field'=>"b.*,a.orderNo,a.recordDate,a.contractId,a.supplierId,a.deliveryDate",
                "where" => "b.coid = '".self::$coid."' and b.sourceId in (select id from purchase_demands where sourceId = '$info[id]')",
                "order" => "b.list desc,b.time desc"));
            static::rSet(self::$stid.self::page.'BuySql',$all['sql']);
            $purchase_num = $receive_num = 0;
            foreach ($all['array'] as $array){
                $contract = query('purchase_contract',"id = '$array[contractId]'");;
                $material = query('material', " id = '$array[materialId]'");
                $supplier = query('supplier', " id = '$array[supplierId]'");
                //退货数量
                $returnAll = find(array(
                    'table'=>"purchase_refund_order as a join purchase_refund_order_detail as b on a.id = b.orderId",
                    'single'=>"a.state = '已确认' and a.coid = '".self::$coid."' and b.sourceId = '$array[id]'"
                ));
                $refundNum = 0;
                foreach ($returnAll['array'] as $val){
                    $refundNum+=machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$array['unit'],$val['num']);
                }
                $array['num'] = self::formattingFigure($array['num']-$refundNum,'numPrecision');
                //收货数量
                $in_num = $this->inInventoryNum($array['id'],$array['unit']);
                $state = '待入库';
                if ($array['num'] > $in_num && $in_num >0){
                    $state = '部分入库';
                }elseif($in_num >= $array['num'] && $in_num >0){
                    $state = '已入库';
                }
                //最后入库日期
                $last = find(array(
                    'table'=>'inventory_detail as a join inventory as b on a.orderId = b.id',
                    'field'=>"date(b.time) as lastDate",
                    'single'=>"a.sourceId in (select id from purchase_get_order_detail where sourceId = '$array[id]')  order by b.time desc"
                ));
                $materialTr[] = array(
                    $array['recordDate'],
                    $array['orderNo'],
                    $contract['orderNo'],
                    $supplier['name'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    self::lostZero($array['num'],'numPrecision'),
                    self::lostZero($in_num,'numPrecision'),
                    self::lostZero($array['num']-$in_num,'numPrecision'),
                    $array['deliveryDate'],
                    $last['lastDate']??'',
                    $state
                );
                $purchase_num += $array['num'];
                $receive_num += $in_num;
            }
            $purchase_total_tr = [
                8 => self::lostZero($purchase_num, 'numPrecision'),
                9 => self::lostZero($receive_num, 'numPrecision'),
                10 => self::lostZero($purchase_num - $receive_num, 'numPrecision'),
            ];

            /*******生产********/
            $processTr[] = ['单据日期','生产派工单号','生产线','工序','产品编码', '产品名称', '规格型号', '单位', '计划生产数量', '完工数量', '未完工数量',  '计划完工时间', '最后入库日期', '状态'];
            $all = find(array(
                'table'=>"machining_send_order",
                "where" => "coid = '".self::$coid."' and state = '已确认' and machiningOrderMxId in (select id from machining_order_mx where (sourceId in (select id from sale_order_detail where orderId = '$info[id]') or sourceId in (select id from product_demands where sourceId = '$info[id]')))",
                "order" => "time desc"));
            static::rSet(self::$stid.self::page.'ProductSql',$all['sql']);
            $product_num = $complete_num = 0;
            foreach ($all['array'] as $array){
                $process = query('process',"id = '$array[processId]'");
                $material = query('material', " id = '$array[materialId]'");
                $line = query('product_line', " id = '$array[lineId]'");
                //入库数量
                $in_num = 0;
                $nmachiningAll = find(array(
                    'table'=>'inventory_detail',
                    'where'=>"sourceId in (select id from machining_in_order_detail where sourceId = '$array[machiningOrderMxId]')"
                ));
                foreach ($nmachiningAll['array'] as $val){
                    $in_num+=machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$array['unit'],$val['num']);
                }
                $in_num = self::formattingFigure($in_num,'numPrecision');
                $state = '待入库';
                if ($array['num'] > $in_num && $in_num >0){
                    $state = '部分入库';
                }elseif($in_num >= $array['num'] && $in_num >0){
                    $state = '已入库';
                }
                //最后入库日期
                $last = find(array(
                    'table'=>'inventory_detail as a join inventory as b on a.orderId = b.id',
                    'field'=>"date(b.time) as lastDate",
                    'single'=>"a.sourceId in (select id from machining_in_order_detail where sourceId = '$array[machiningOrderMxId]')  order by b.time desc"
                ));
                $processTr[] = array(
                    $array['recordDate'],
                    $array['orderNo'],
                    $line['workshop'].'-'.$line['name'],
                    $process['name'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    self::lostZero($array['num'],'numPrecision'),
                    self::lostZero($in_num,'numPrecision'),
                    self::lostZero($array['num']-$in_num,'numPrecision'),
                    $array['endDate'],
                    $last['lastDate']??'',
                    $state
                );
                $product_num += $array['num'];
                $complete_num += $in_num;
            }
            $product_total_tr = [
                8 => self::lostZero($product_num, 'numPrecision'),
                9 => self::lostZero($complete_num, 'numPrecision'),
                10 => self::lostZero($product_num - $complete_num, 'numPrecision'),
            ];

            $button = [];
            if ($this->power(self::page, "export")) {
                $button[] = [
                    "name" => '导出',
                    "type" => "外部链接",
                    "url" => root . "control/adIndex.html?cla=" . $this->get('cla') . "&fun=exportDetail",
                    'style' => 'li-btn-blue-bg',
                ];
            }
            //生成表单
            $data['button'] = $this->tableShowButton($button);
            $kehu  = query('kehu', "khid = '$info[khid]'", "companyName");
            $data['html'] = $this->tableShow(array(
                '销售订单' => array(
                    array(
                        '销售订单号'=>$info['orderNo'],
                        '销售员'=>self::findStaff($info['manager']),
                        '客户名称'=>$kehu['companyName'],
                        '交货日期'=>$info['deliveryDate'],
                    )
                ),
            ));
            $data['html'] .= $this->detailList([
                'title' => '商品清单',
                'html' => $this->listTable(array('tr' => $reportTr, 'showEmpty' => true, 'total' => $slae_total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '采购进度',
                'html' => $this->listTable(array('tr' => $materialTr, 'showEmpty' => true, 'total' => $purchase_total_tr, 'showSort' => true)),
            ]);
            $data['html'] .= $this->detailList([
                'title' => '生产进度',
                'html' => $this->listTable(array('tr' => $processTr, 'showEmpty' => true, 'total' => $product_total_tr, 'showSort' => true)),
            ]);
            //生成页面
            $html = $this->tab($data);
        }
        //返回
        return $html;
    }

    /**
     * 导出详情
     */
    public function exportDetail()
    {
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有编辑的权限';
        } else {
            $orderNo = static::rGet(self::$stid.self::page.'OrderNo');
            $text   = $this->control['name'] . "导出了销售订单{$orderNo}跟踪详情";
            $this->logText(["type" => self::page, "text" => $text]);
            $title  = ['单据日期', '单据编号', '合同编号', '客户','销售员', '产品编码', '产品名称',  '规格型号', '单位', '销售数量', '发货数量', '未发货数量','交货日期','最后出库日期','状态'];
            $reportTr = [];
            $sql = static::rGet(self::$stid.self::page.'SaleSql');
            $result = sqlFind($sql);
            if (is_array($result)) {
                foreach ($result as $array) {
                    $contract = query('sales_contract',"id = '$array[contractId]'");
                    $kehu = query('kehu',"khid = '$array[khid]'");
                    //已出库数量
                    $out_num = $this->outInventoryNum($array['id'],$array['unit']);

                    $state = '待出库';
                    if ($array['num'] > $out_num && $out_num >0){
                        $state = '部分出库';
                    }elseif($out_num >= $array['num'] && $out_num >0){
                        $state = '已出库';
                    }
                    //最后出库日期
                    $last = find(array(
                        'table'=>'inventory_detail as a join inventory as b on a.orderId = b.id',
                        'field'=>"date(b.time) as lastDate",'single'=>"a.sourceId in (select id from sale_send_order_detail where saleOrderMxId = '$array[id]') order by b.time desc"
                    ));
                    $reportTr[] = array(
                        $array['recordDate'],
                        $array['orderNo'],
                        $contract['orderNo'],
                        $kehu['companyName'],
                        self::findStaff($array['stid']),
                        $array['code'],
                        $array['materialName'],
                        $array['model'],
                        $array['unit'],
                        self::lostZero($array['num'],'numPrecision'),
                        self::lostZero($out_num,'numPrecision'),
                        self::lostZero($array['num']-$out_num,'numPrecision'),
                        $array['deliveryDate'],
                        isset($last['lastDate'])&&$state!='待出库'?$last['lastDate']:'',
                        $state
                    );
                }
            }

            /****采购******/
            $materialTr = [];
            $sql = static::rGet(self::$stid.self::page.'BuySql');
            $result = sqlFind($sql);
            foreach ($result as $array){
                $contract = query('purchase_contract',"id = '$array[contractId]'");
                $material = query('material', " id = '$array[materialId]'");
                $supplier = query('supplier', " id = '$array[supplierId]'");
                //退货数量
                $returnAll = find(array(
                    'table'=>"purchase_refund_order as a join purchase_refund_order_detail as b on a.id = b.orderId",
                    'single'=>"a.state = '已确认' and a.coid = '".self::$coid."' and b.sourceId = '$array[id]'"
                ));
                $refundNum = 0;
                foreach ($returnAll['array'] as $val){
                    $refundNum+=machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$array['unit'],$val['num']);
                }
                $array['num'] = self::formattingFigure($array['num']-$refundNum,'numPrecision');
                //收货数量
                $in_num = $this->inInventoryNum($array['id'],$array['unit']);
                $state = '待入库';
                if ($array['num'] > $in_num && $in_num >0){
                    $state = '部分入库';
                }elseif($in_num >= $array['num'] && $in_num >0){
                    $state = '已入库';
                }
                //最后入库日期
                $last = find(array(
                    'table'=>'inventory_detail as a join inventory as b on a.orderId = b.id',
                    'field'=>"date(b.time) as lastDate",
                    'single'=>"a.sourceId in (select id from purchase_get_order_detail where sourceId = '$array[id]')  order by b.time desc"
                ));
                $materialTr[] = array(
                    $array['recordDate'],
                    $array['orderNo'],
                    $contract['orderNo'],
                    $supplier['name'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    self::lostZero($array['num'],'numPrecision'),
                    self::lostZero($in_num,'numPrecision'),
                    self::lostZero($array['num']-$in_num,'numPrecision'),
                    $array['deliveryDate'],
                    $last['lastDate']??'',
                    $state
                );
            }

            /*******生产********/
            $processTr= [];
            $sql = static::rGet(self::$stid.self::page.'ProductSql');
            $result = sqlFind($sql);
            foreach ($result as $array){
                $process = query('process',"id = '$array[processId]'");
                $material = query('material', " id = '$array[materialId]'");
                $line = query('product_line', " id = '$array[lineId]'");
                //入库数量
                $in_num = 0;
                $nmachiningAll = find(array(
                    'table'=>'inventory_detail',
                    'where'=>"sourceId in (select id from machining_in_order_detail where sourceId = '$array[machiningOrderMxId]')"
                ));
                foreach ($nmachiningAll['array'] as $val){
                    $in_num+=machiningOrderClass::material_num_change($val['materialId'],$val['unit'],$array['unit'],$val['num']);
                }
                $in_num = self::formattingFigure($in_num,'numPrecision');
                $state = '待入库';
                if ($array['num'] > $in_num && $in_num >0){
                    $state = '部分入库';
                }elseif($in_num >= $array['num'] && $in_num >0){
                    $state = '已入库';
                }
                //最后入库日期
                $last = find(array(
                    'table'=>'inventory_detail as a join inventory as b on a.orderId = b.id',
                    'field'=>"date(b.time) as lastDate",
                    'single'=>"a.sourceId in (select id from machining_in_order_detail where sourceId = '$array[machiningOrderMxId]')  order by b.time desc"
                ));
                $processTr[] = array(
                    $array['recordDate'],
                    $array['orderNo'],
                    $line['workshop'].'-'.$line['name'],
                    $process['name'],
                    $material['code'],
                    $material['name'],
                    $material['model'],
                    $array['unit'],
                    self::lostZero($array['num'],'numPrecision'),
                    self::lostZero($in_num,'numPrecision'),
                    self::lostZero($array['num']-$in_num,'numPrecision'),
                    $array['endDate'],
                    $last['lastDate']??'',
                    $state
                );
            }
            $temp = ini_get('upload_tmp_dir');
            if ($temp !== false && file_exists($temp)) {
                $tempDir = realpath($temp);
            } else {
                $tempDir  = realpath(sys_get_temp_dir());
            }
            $config=[];
            if (PHP_OS == 'Linux') {
                $config = [
                    'path' => $tempDir . '/',
                ];
            } elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                //windows环境
                $config = [
                    'path' => $tempDir,
                ];
            }
            $excel    = new \Vtiful\Kernel\Excel($config);
            $fileObject = $excel->fileName("销售订单{$orderNo}跟踪详情.xlsx",'销售');
            $fileObject->header($title)
                ->data($reportTr);
            $title  = ['单据日期','采购订单号','合同编号','供应商','产品编码', '产品名称',  '规格型号', '单位', '采购数量', '收货数量', '未收货数量',  '交货日期', '最后入库日期', '状态'];
            $fileObject->addSheet('采购')
                ->header($title)
                ->data($materialTr);

            $title  =  ['单据日期','生产派工单号','生产线','工序','产品编码', '产品名称', '规格型号', '单位', '计划生产数量', '完工数量', '未完工数量',  '计划完工时间', '最后入库日期', '状态'];
            $fileObject->addSheet('生产')
                ->header($title)
                ->data($processTr);


            $filePath=$fileObject->output();
            if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
                //windows环境
                $filePath = str_replace("/", "\\", $filePath);
//                $filePath = iconv("UTF-8", "GBK//IGNORE", $filePath);
            }
            header("Content-Type: applicationnd.openxmlformats-officedocument.spreadsheetml.sheet");
            header('Content-Disposition: attachment;filename="销售订单'.$orderNo.'跟踪详情.xlsx"');
            header('Cache-Control: max-age=0');
            ob_clean();
            flush();
            if (copy($filePath, 'php://output') === false) {
                // Throw exception
            }
            @unlink($filePath);
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出
     */
    public function exportData()
    {
        $templateId = $this->get('templateId');
        $checkedId = $this->get('checkedId')?explode(',',$this->get('checkedId')):[];
        if (!$this->power(self::page, 'export')) {
            $_SESSION['warn'] = '你还没有导出的权限';
        }   else {
            $data = [];
            /***********标题**********/
            $title =[];
            $tempFieldAll = importTemplateClass::templateField(self::page, 'exportFieldInit', id:$templateId);
            foreach ($tempFieldAll as $array) {
                if ($array['display']){
                    $title[] = $array['aliasName'];
                }
            }
            //判断是否选中导出
            if (!self::is_null_array($checkedId)){
                $result = find(array(
                    "table" => 'sale_order',
                    "where" => "id in ('".implode("','", $checkedId)."') order by recordDate desc,time desc",
                ))['array'];
            }else{
                $sql   = $_SESSION[self::page]['sql'];
                $result   = sqlFind($sql);
            }
            //导出数据生成
            foreach ($result as $array){
                $column = [];
                $contract = query('sales_contract',"id = '$array[contractId]'");
                $kehu = query('kehu',"khid = '$array[khid]'");
                $state = '待出库';
                if ($array['num'] > $array['send_num'] && $array['send_num'] >0){
                    $state = '部分出库';
                }elseif($array['send_num'] >= $array['num'] && $array['send_num'] >0){
                    $state = '已出库';
                }
                foreach ($tempFieldAll as $templateField){
                    if ($templateField['display']){
                        $column[] = match ($templateField['columnName']){
                            '单据日期'=>$array['recordDate'],
                            '单据编号'=>$array['orderNo'],
                            '合同编号'=> $contract['orderNo'],
                            '客户'=> $kehu['companyName'],
                            '销售员'=>self::findStaff($array['manager']),
                            '订单总数量'=>self::lostZero($array['num'],'numPrecision'),
                            '发货总数量'=>self::lostZero($array['send_num'],'numPrecision'),
                            '剩余总数量'=>self::lostZero($array['num']-$array['send_num']+ $array['refund_num'],'numPrecision'),
                            '交货日期'=>$array['deliveryDate'],
                            '状态'=>$state,
                            '退货总数量'=>self::lostZero($array['refund_num'], 'numPrecision'),
                            '完成率'=>($array['completion_rate'] * 100) . '%',
                            default=>'',
                        };
                    }
                }
                $data[] = $column;
            }
            $text = $this->control['name'] . "导出了销售订单跟踪表";
            $this->logText(["type" => self::page, "text" => $text]);
            $this->excelOut($title, $data, "销售订单跟踪表.xlsx");
            exit(0);
        }
        header("Location:" . getenv("HTTP_REFERER"));
    }

    /**
     * 导出模板字段初始化
     * @return array[]
     */
    public function exportFieldInit($classify=''): array
    {
        return match ($classify) {
            default=>  [
                [
                    'columnName'=>'单据日期',
                    'aliasName'=>'单据日期',
                ],
                [
                    'columnName'=>'单据编号',
                    'aliasName'=>'单据编号',
                ],
                [
                    'columnName'=>'合同编号',
                    'aliasName'=>'合同编号',
                ],
                [
                    'columnName'=>'客户',
                    'aliasName'=>'客户',
                ],
                [
                    'columnName'=>'销售员',
                    'aliasName'=>'销售员',
                ],
                [
                    'columnName'=>'订单总数量',
                    'aliasName'=>'订单总数量',
                ],
                [
                    'columnName'=>'发货总数量',
                    'aliasName'=>'发货总数量',
                ],
                [
                    'columnName'=>'退货总数量',
                    'aliasName'=>'退货总数量',
                ],
                [
                    'columnName'=>'剩余总数量',
                    'aliasName'=>'剩余总数量',
                ],
                [
                    'columnName'=>'完成率',
                    'aliasName'=>'完成率',
                ],
                [
                    'columnName'=>'交货日期',
                    'aliasName'=>'交货日期',
                ],
                [
                    'columnName'=>'状态',
                    'aliasName'=>'状态',
                ],
            ]
        };
    }
}

